@echo off
title 自动检测IP并启动服务器
color 0A

echo.
echo ╔══════════════════════════════════════════════════════════════╗
echo ║              自动检测IP并启动服务器                          ║
echo ╚══════════════════════════════════════════════════════════════╝
echo.

cd /d "%~dp0"

echo 🔍 检测当前IP地址...
for /f "tokens=2 delims=:" %%i in ('ipconfig ^| findstr /i "IPv4"') do (
    set "IP=%%i"
    set "IP=!IP: =!"
    if not "!IP!"=="" (
        echo ✅ 检测到IP地址: !IP!
        goto :found_ip
    )
)

:found_ip
if "%IP%"=="" (
    echo ❌ 无法检测到IP地址，使用默认地址
    set "IP=192.168.1.6"
)

echo.
echo 🔧 更新配置文件中的IP地址...
powershell -Command "(Get-Content 'js/services/api/config.js') -replace 'http://[0-9.]+:3002/api', 'http://%IP%:3002/api' | Set-Content 'js/services/api/config.js'"

echo.
echo 🚀 启动服务器...
pm2 delete all >nul 2>&1
pm2 start backend/server.js --name "neighborhood-help-backend"
pm2 save

echo.
echo ⏳ 等待服务器启动...
timeout /t 3 /nobreak >nul

echo.
echo 🔍 测试服务器连接...
curl -s http://%IP%:3002/api/health >nul 2>&1
if errorlevel 1 (
    echo ❌ 服务器连接失败，请检查错误日志
    pm2 logs neighborhood-help-backend --lines 5
) else (
    echo ✅ 服务器启动成功！
)

echo.
echo 📊 当前状态:
pm2 status

echo.
echo 🌐 服务器地址: http://%IP%:3002/api
echo 📱 小程序配置已自动更新为当前IP地址

echo.
pause
